import { useUserStore } from '@/stores/userStore';
import { ElMessage } from 'element-plus'
import { extend, type RequestResponse } from 'umi-request';
import { options } from './options';
const userStore = useUserStore();
const instance = extend({
  ...options
});
// 可选：请求拦截器
instance.interceptors.request.use((url, options) => {
  // 例如自动加 token
  const token = userStore.token;
  if (token) {
    options.headers = { ...options.headers, Authorization: `Bearer ${token}` };
  }
  return { url, options };
});

// 可选：响应拦截器
instance.interceptors.response.use(async (response, options) => {
  // 可在此统一处理响应数据

  if (response.status === 401) {
    // token 过期，跳转到登录页
    // 清除本地 token 等信息
    ElMessage.error('登录已过期，请重新登录');

    userStore.logout();

    // 跳转登录页（根据你的路由实际调整）
    // window.location.href = '/login';
  }
  if (response.status === 500) {
    // 服务器错误
    console.log(ElMessage,'+++++++++++');
    console.error('服务器错误', response);
    ElMessage.error('服务器错误');

  }
  return response;
});



// 通用 request 方法
const request = <T = any>(url: string, config: any = {}) => {
  return instance(url, config) as Promise<RequestResponse<T>>;
};

// get 方法：request.get(url, paramsObj)
request.get = <T = any>(url: string, params?: Record<string, any>, config: any = {}) => {
  return instance(url, {
    method: 'get',
    params,
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// post 方法：request.post(url, { data: {} }) 或 request.post(url, dataObj)
request.post = <T = any>(url: string, data?: any, config: any = {}) => {
  // 兼容 request.post(url, { data: {} }) 和 request.post(url, dataObj)
  const postData = data && data.data !== undefined ? data.data : data;
  return instance(url, {
    method: 'post',
    data: postData,
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// put 方法
request.put = <T = any>(url: string, data?: any, config: any = {}) => {
  const putData = data && data.data !== undefined ? data.data : data;
  return instance(url, {
    method: 'put',
    data: putData,
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// delete 方法
request.delete = <T = any>(url: string, params?: Record<string, any>, config: any = {}) => {
  return instance(url, {
    method: 'delete',
    params,
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// patch 方法
request.patch = <T = any>(url: string, data?: any, config: any = {}) => {
  const patchData = data && data.data !== undefined ? data.data : data;
  return instance(url, {
    method: 'patch',
    data: patchData,
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// head 方法
request.head = <T = any>(url: string, config: any = {}) => {
  return instance(url, {
    method: 'head',
    ...config,
  }) as Promise<RequestResponse<T>>;
};

// 支持取消请求
request.createAbortController = () => {
  return new AbortController();
};

export default request;
